#include <math.h>
#include <string.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <glib.h>
#include <glib-object.h>

//#include "object.h"
#include "httpd.h"
#ifndef SOFTWARE_NAME
#define SOFTWARE_NAME "webrobot"
#endif
#define PI 3.14
#define DEFAULT_LINEAR 1
#define DEFAULT_ANGULAR 1

char *control_callback(const char *method, const char *url,
    const char *data, void *user_data)
{
  char *res = NULL;

  g_debug("[++++]L%d method:%s url:%s data:%s//end",
      __LINE__, method, url, data);
  if (!strcmp(url, "/shell")) {
    system(data);
    char *sucess = "<test>success</test>", *now = NULL;
    now = sucess;
    res = calloc(1, strlen(now)+1);
    strcpy(res, now);
  }
  return res;
}
char *callback(const char *method, const char *url, const char *data,
    void *user_data)
{
  char *res = NULL;

  printf("timestamp:%"G_GINT64_FORMAT, g_get_real_time());
  printf("[++++]L%d method:%s url:%s data:%s\n", __LINE__, method, url, data);
  res = control_callback(method, url, data, user_data);
  return res;
}
int main (int argc, char **argv)
{
  int port = 80;
  char *webRoot = NULL;

  if (argc == 4) {
    port = atoi(argv[2]);
    webRoot = argv[3];
  }
  printf("port:%d webRoot:%s \n", port, webRoot);
  void *d = httpd_start1(port, callback, webRoot, NULL);
  g_debug("L%d HTTP server running on:%d", __LINE__, port);
  if (d == NULL)
    return 1;
  if (getppid() == 1) {
    //system
    while (1) {
      sleep(1);
    }
  } else {
    (void) getc (stdin);
  }
  httpd_stop(d);
  return 0;
}

